<template>
  <div class="digital-human-avatar">
    <div class="avatar-container" :class="{ 'is-loading': avatarLoading, 'is-loaded': !avatarLoading }">
      <!-- 加载动画 -->
      <div v-if="avatarLoading" class="avatar-loading">
        <div class="loading-dots">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
        <p class="loading-text">数字人加载中...</p>
      </div>
      
      <!-- 数字人视频 -->
      <video 
        ref="videoRef" 
        class="avatar-video"
        autoplay
        muted
        playsinline
        @canplay="onVideoCanPlay"
        @timeupdate="onVideoTimeUpdate"
        @error="onVideoError"
      />
      
      <!-- 视频背景效果 -->
      <div class="video-background"></div>
    </div>
    
    <!-- 数字人信息 -->
    <div class="avatar-info">
      <div class="avatar-status">
        <div class="status-indicator" :class="statusClass"></div>
        <span class="status-text">{{ statusText }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import type { DigitalHumanController } from '../controller/DigitalHumanController'

// Props
interface Props {
  controller: DigitalHumanController | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  avatarLoaded: []
}>()

// 响应式数据
const videoRef = ref<HTMLVideoElement | null>(null)
const avatarLoading = ref(true)
const videoError = ref(false)
const agentStatus = ref<string>('connecting')

// 计算属性
const statusClass = computed(() => {
  switch (agentStatus.value) {
    case 'connected':
      return 'status-connected'
    case 'speaking':
      return 'status-speaking'
    case 'listening':
      return 'status-listening'
    case 'error':
      return 'status-error'
    default:
      return 'status-connecting'
  }
})

const statusText = computed(() => {
  switch (agentStatus.value) {
    case 'connected':
      return '已连接'
    case 'speaking':
      return '正在说话'
    case 'listening':
      return '正在聆听'
    case 'error':
      return '连接错误'
    default:
      return '连接中'
  }
})

// 视频事件处理
const onVideoCanPlay = () => {
  console.log('Avatar video can play')
  avatarLoading.value = false
  emit('avatarLoaded')
}

const onVideoTimeUpdate = () => {
  if (avatarLoading.value) {
    avatarLoading.value = false
    emit('avatarLoaded')
  }
}

const onVideoError = (event: Event) => {
  console.error('Avatar video error:', event)
  videoError.value = true
  avatarLoading.value = false
  agentStatus.value = 'error'
}

// 添加视频背景效果
const addVideoBackground = (video: HTMLVideoElement) => {
  // 检查是否为移动设备
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  if (isMobile) return

  try {
    // 创建canvas用于背景效果
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    if (!ctx) return

    canvas.width = video.videoWidth || 512
    canvas.height = video.videoHeight || 512
    canvas.style.position = 'absolute'
    canvas.style.top = '0'
    canvas.style.left = '0'
    canvas.style.width = '100%'
    canvas.style.height = '100%'
    canvas.style.zIndex = '-1'
    canvas.style.filter = 'blur(20px) brightness(0.3)'
    canvas.style.transform = 'scale(1.2)'

    // 将canvas添加到视频容器
    const container = video.parentElement
    if (container) {
      container.appendChild(canvas)
    }

    // 定期更新背景
    const updateBackground = () => {
      if (video.videoWidth > 0 && video.videoHeight > 0) {
        canvas.width = video.videoWidth
        canvas.height = video.videoHeight
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      }
      requestAnimationFrame(updateBackground)
    }

    video.addEventListener('loadeddata', updateBackground)
  } catch (error) {
    console.warn('Failed to add video background:', error)
  }
}

// 监听控制器变化
watch(() => props.controller, (newController) => {
  if (newController && videoRef.value) {
    // 设置视频元素到控制器
    newController.setAgentView(videoRef.value)
    
    // 监听控制器事件
    newController.on('agentStateChanged', (state: string) => {
      agentStatus.value = state.toLowerCase()
    })
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  if (videoRef.value) {
    // 添加视频背景效果
    addVideoBackground(videoRef.value)
    
    // 如果控制器已存在，设置视频元素
    if (props.controller) {
      props.controller.setAgentView(videoRef.value)
    }
  }
})

onUnmounted(() => {
  // 清理资源
  if (videoRef.value) {
    videoRef.value.srcObject = null
  }
})
</script>

<style scoped>
.digital-human-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.avatar-container {
  width: 100%;
  max-width: 512px;
  height: 100%;
  max-height: 512px;
  position: relative;
  border-radius: 1rem;
  overflow: hidden;
  background: linear-gradient(45deg, #667eea, #764ba2);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.avatar-container.is-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.avatar-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
}

.loading-dots {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.loading-dots span {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: white;
  animation: loading-bounce 1.4s ease-in-out infinite both;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }
.loading-dots span:nth-child(3) { animation-delay: 0s; }
.loading-dots span:nth-child(4) { animation-delay: 0.16s; }
.loading-dots span:nth-child(5) { animation-delay: 0.32s; }

@keyframes loading-bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.loading-text {
  font-size: 1rem;
  font-weight: 500;
  margin: 0;
  opacity: 0.8;
}

.avatar-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 1rem;
}

.video-background {
  position: absolute;
  top: -10%;
  left: -10%;
  width: 120%;
  height: 120%;
  background: inherit;
  filter: blur(20px) brightness(0.3);
  z-index: -1;
}

.avatar-info {
  position: absolute;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(10px);
  padding: 0.5rem 1rem;
  border-radius: 2rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.avatar-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-connecting {
  background: #ffc107;
}

.status-connected {
  background: #28a745;
}

.status-speaking {
  background: #007bff;
  animation: pulse 0.5s infinite;
}

.status-listening {
  background: #17a2b8;
}

.status-error {
  background: #dc3545;
  animation: none;
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .avatar-container {
    max-width: 100%;
    max-height: 60vh;
  }
  
  .avatar-info {
    bottom: 0.5rem;
    padding: 0.25rem 0.75rem;
    font-size: 0.75rem;
  }
}
</style>
